package com.scs.application.modules.fsd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.fsd.entity.FsdGroupUser;
import com.scs.application.modules.fsd.mapper.GroupUserMapper;
import com.scs.application.modules.fsd.service.GroupUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 */
@Service
public class GroupUserServiceImpl extends BaseServiceImpl<GroupUserMapper, FsdGroupUser> implements GroupUserService {

    /**
     * 为群组指定用户
     * @param userIds
     * @param groupId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean saveGroupUser(String userIds, String groupId) {
        //先删除此组的成员
        remove(new QueryWrapper<FsdGroupUser>().eq("group_id", groupId));
        //将用户列表保存
        Collection<FsdGroupUser> groupUsers = new ArrayList<>();
        String[] userIdArray = userIds.split(",");
        for (String user_id : userIdArray) {
            if (StringUtils.isBlank(user_id)) continue;
            FsdGroupUser groupUser = new FsdGroupUser();
            groupUser.setGroupId(groupId);
            groupUser.setUserId(user_id);
            groupUsers.add(groupUser);
        }
        saveBatch(groupUsers);
        return true;
    }

    /**
     * 为用户分配群组
     * @param userId
     * @param groupIds
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean saveGroupsByUser(String userId, String groupIds) {
        //先删除此用户所有的组
        remove(new QueryWrapper<FsdGroupUser>().eq("user_id", userId));
        //将用户组列表保存
        Collection<FsdGroupUser> groupUsers = new ArrayList<>();
        String[] groupIdArray = groupIds.split(",");
        for (String group_id : groupIdArray) {
            if (StringUtils.isBlank(group_id)) continue;
            FsdGroupUser groupUser = new FsdGroupUser();
            groupUser.setGroupId(group_id);
            groupUser.setUserId(userId);
            groupUsers.add(groupUser);
        }
        saveBatch(groupUsers);
        return true;
    }

    @Override
    public List<FsdGroupUser> getUsersByGroupId(String id) {
        return baseMapper.getUsersByGroupId(id);
//        return this.list(new QueryWrapper<FsdGroupUser>().eq("group_id", id));
    }

    @Override
    public  List<Map<String,Object>> getGroupByUserId(String id) {
        return baseMapper.getGroupByUserId(id);
//        return this.list(new QueryWrapper<FsdGroupUser>().eq("user_id", id));
    }
}
